/*
 * @Author: anshengtyp
 * @Date: 2024-03-19 16:06:29
 * @LastEditTime: 2024-03-21 16:24:42
 * @LastEditors: anshengtyp
 * @Description: 
 */

import { createCanvas, loadImage } from 'canvas';
import { mimeType } from "./tools";
const canvas = createCanvas();
const ctx = canvas.getContext('2d');

function getDataURL(imgData, extension) {
  canvas.width = imgData.width;
  canvas.height = imgData.height;
  ctx.putImageData(imgData, 0, 0);
  return new Promise(resolve => {
    canvas.toBlob(blob => resolve(blob), mimeType[extension], 1);
  });
}

const convertImage = (src, usrOptions) => {
  const options = {
    rotation: 180,
    interpolation: 'lanczos',
    outformat: 'jpg',
    outtype: 'file',
    width: Infinity,
    ...usrOptions
  }
  return new Promise(resolve => {
    loadImage(src).then((img) => {
      const { width, height } = img;
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0);
      const data = ctx.getImageData(0, 0, width, height);
      processImage(data, options).then(x => resolve(x));
    })
  });
}

// 其他代码保持不变，只修改processFace函数
const processFace = (data, options, facename) => {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL('./convert.js', import.meta.url), {
      type: 'module',
    });

    const optionsData = {
      data,
      face: facename,
      rotation: Math.PI * options.rotation / 180,
      interpolation: options.interpolation,
      maxWidth: options.width
    };

    worker.postMessage(optionsData); // 向worker发送数据

    worker.onmessage = function (e) {
      const { result } = e.data;
      getDataURL(result, options.outformat).then(file => {
        let result = new File([file], facename + '.' + options.outformat, { type: "image/" + options.outformat, lastModified: Date.now() });
        resolve(result);
      });
      worker.terminate(); // 处理完成后终止worker
    };

    worker.onerror = function (error) {
      reject(error);
      worker.terminate();
    };
  });
}

const processImage = (data, options) => {
  const faces = ["pz", "nz", "px", "nx", "py", "ny"].map(face => processFace(data, options, face))
  return new Promise(resolve => Promise.all(faces).then(x => resolve(x)));
}


export {
  convertImage
}